import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useModel } from "umi";
import "./index.less";
import OpeningReportForms from "./OpeningReportForms";
import SubjectForms from "./SubjectForms";
// import { AntTabs } from 'antd';
import AntTabs from '~/public/cpas-ui/components-ui/ant-components/AntTab';

import PubSub from 'pubsub-js'; // 组件互相通讯的插件
import { intl } from "@/utils";
import { SelectBox, CheckBox, Button } from "devextreme-react";
import { CpasIcon } from "~/public/cpas-ui";
import { getAccountInfo } from "./service";

const OpeningCheck1 = (props: any) => {
    const { initialState } = useModel('@@initialState');
    const { dbname, sjnd } = initialState?.curPart as API.CurPart || {};
    const [valIndex, setValIndex] = useState<string>('1');

    const Divstyle: React.CSSProperties = { display: 'flex', alignItems: "center", justifyContent: "center", };
    const DivstyleBox: React.CSSProperties = { display: 'flex', alignItems: "center", justifyContent: "space-between" };
    const Titlestyle: React.CSSProperties = { marginRight: "8px" };
    const [accountData, setAccountData] = useState<any[]>([]);
    const [slectYearData, setSelectYearData] = useState<any>({
        Data_ID: '',
        index: 0
    });
    const [checkBoxVaue, setCheckBoxVaue] = useState<boolean>(false);
    const refsOpeningReportForms = useRef<any>(null);
    const refsSubjectForms = useRef<any>(null);
    // 
    const singleReloadTable = (yearID: string, checkBox: boolean) => {
        if (valIndex === '1') {
            if (refsOpeningReportForms.current) {
                refsOpeningReportForms.current.reloadDevTable(yearID, checkBox);
            }
        } else {
            if (refsSubjectForms.current) {
                refsSubjectForms.current.reloadDevTable(yearID, checkBox);
            }
        }
    }


    const changeTabsKey = useCallback((val: string) => {
        setValIndex(val);
    }, []);

    // 无差异不显示
    const onValueChangeds = useCallback((e: any) => {
        setCheckBoxVaue(e.value);
    }, []);

    // 获取列表的点击项 
    const onSelectionChangeds = useCallback((e: any) => {
        let selectDefaultIDs = { yearFinancial: e.selectedItem.Data_ID };
        // // 本地存储 持久化数据
        window.localStorage.setItem(`selectOpeningTool_${dbname}`, JSON.stringify(selectDefaultIDs))
        setSelectYearData({
            Data_ID: e.selectedItem.Data_ID,
            index: e.selectedItem.index
        });
    }, []);




    /**
      *获取账套年度数据
      */
    const fetchYearData = useCallback(async () => {
        const auditAdjustId: any = window.localStorage.getItem(`selectOpeningTool_${dbname}`);
        const tempYear = JSON.parse(auditAdjustId)?.yearFinancial ?? sjnd;
        let findTemp = -2;
        const res: any = await getAccountInfo({ dbname });
        if (res.success) {
            findTemp = res.data.findIndex((item: any) => {
                return tempYear === item.Data_ID
            });
            const tempIndex = findTemp >= 0 ? findTemp : 0;
            const DataId = res.data[tempIndex]?.Data_ID;
            console.log(DataId, 'DataId----------');
            window.localStorage.setItem(`selectOpeningTool_${dbname}`, JSON.stringify({ yearFinancial: DataId }));
            setSelectYearData({
                Data_ID: DataId,
                index: tempIndex
            });
            res.data.forEach((item: any, index: any) => {
                item.index = index
                return item
            });
            setAccountData(res.data);
        }

    }, []);


    useEffect(() => {
        fetchYearData();
    }, []);

    return (<div className="openingCheck_whole">
        <div style={DivstyleBox}>
            <div style={Divstyle}>
                <div style={Divstyle}>
                    <div style={Titlestyle}>{intl('report.subject.account', '账套:')}</div>
                    <SelectBox
                        width={200}
                        dataSource={accountData}
                        displayExpr='displayName'
                        valueExpr='displayName'
                        value={accountData[slectYearData.index || 0]?.displayName ?? ""}
                        onSelectionChanged={onSelectionChangeds}
                        dropDownOptions={
                            { width: '400px' }
                        }
                    />
                </div>
                <div style={{ ...Divstyle, marginLeft: 15 }}>
                    <CheckBox className='SubjectsCheckBox' onValueChanged={onValueChangeds} /><span style={{ marginLeft: "5px" }}>无差异不显示</span>

                </div>
            </div>
            <div>

                <Button
                    className="defaultReloadBtnWhite"
                    render={() => (<CpasIcon type='icon-refresh' fontSize={16} />)}
                    onClick={() => {
                        singleReloadTable(slectYearData.Data_ID, checkBoxVaue);
                    }} />
            </div>
        </div>

        <AntTabs defaultActiveKey="1"
            onChange={(val: string) => { changeTabsKey(val) }} activeKey={valIndex}>
            <AntTabs.TabPane tab="期初报表核对" key="1" id="tabsPaneH">
                <OpeningReportForms ref={refsOpeningReportForms} slectYearData={{ ...slectYearData, checkBoxVaue }} />
            </AntTabs.TabPane>
            <AntTabs.TabPane tab="期初科目核对" key="2" id="tabsPaneH">
                <SubjectForms ref={refsSubjectForms} slectYearData={{ ...slectYearData, checkBoxVaue }} />
            </AntTabs.TabPane>
        </AntTabs>
    </div>)
}
export default OpeningCheck1;